package com.test.com.bluetoothchatandroid.activity;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.orhanobut.logger.Logger;
import com.test.com.bluetoothchatandroid.R;
import com.test.com.bluetoothchatandroid.adapter.ChatAdapter;
import com.test.com.bluetoothchatandroid.base.BaseActivity;
import com.test.com.bluetoothchatandroid.callback.BluetoothChatCallback;
import com.test.com.bluetoothchatandroid.entity.BaseMessage;
import com.test.com.bluetoothchatandroid.entity.ChatInfo;
import com.test.com.bluetoothchatandroid.entity.FileMessage;
import com.test.com.bluetoothchatandroid.entity.FriendInfo;
import com.test.com.bluetoothchatandroid.global.BluetoothState;
import com.test.com.bluetoothchatandroid.global.ChatConstant;
import com.test.com.bluetoothchatandroid.global.Constant;
import com.test.com.bluetoothchatandroid.utils.BluetoothChatHelper;
import com.test.com.bluetoothchatandroid.utils.CommandHelper;
import com.test.com.bluetoothchatandroid.utils.DateTime;
import com.test.com.bluetoothchatandroid.utils.HexUtil;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author saviorT
 */
public class ChatActivity extends BaseActivity {

	@BindView(R.id.center_title)
	TextView centerTitle;
	@BindView(R.id.toolbar)
	Toolbar toolbar;
	@BindView(R.id.chat_msg_edit)
	EditText chatMsgEdit;
	@BindView(R.id.chat_emojicons)
	FrameLayout chatEmojicons;
	@BindView(R.id.listView)
	ListView listView;
	@BindView(R.id.bottomLl)
	LinearLayout bottomLl;


	//	private static final String NAME = "friendsName";
	//	private static final String BUNDLE = "bundle";

	private FriendInfo mFriendInfo;
	private List<ChatInfo> mChatInfoList = new ArrayList<>();
	//	private MyChatAdapter mAdapter;
	private ChatAdapter mAdapter;
	private boolean mIsSendFile = false;
	private File mSendFile;
	private String mFilePath;
	private ProgressDialog mProgressDialog;

	private BluetoothChatCallback<byte[]> chatCallback = new BluetoothChatCallback<byte[]>() {
		@Override
		public void connectStateChange(BluetoothState state) {
			Logger.d("连接状态改变：" + state.getCode());
			if (state == BluetoothState.STATE_CONNECTED) {
				if (mProgressDialog != null) {
					mProgressDialog.hide();
				}
				if (mFriendInfo != null) {
					centerTitle.setText(mFriendInfo.getFriendNickName() + "(在线)");
				}
				showToast("连接成功");
			}
		}

		@Override
		public void writeData(byte[] data, int type) {
			if (data == null) {
				Logger.d("写入数据为空或未写入");
				return;
			}
			Logger.d("写入数据为：" + HexUtil.encodeHexStr(data));
		}

		@Override
		public void readData(byte[] data, int type) {
			if (data == null) {
				Logger.d("读取数据为空或没有可读取数据");
				return;
			}
			Logger.d("readData：" + HexUtil.encodeHexStr(data));
			try {
				BaseMessage message = CommandHelper.unpackData(data);
				ChatInfo chatInfo = new ChatInfo();
				chatInfo.setMessage(message);
				chatInfo.setReceiveTime(DateTime.getStringByFormat(new Date(), DateTime.DEFYMDHMS));
				chatInfo.setSend(false);
				chatInfo.setFriendInfo(mFriendInfo);
				mChatInfoList.add(chatInfo);
				Logger.d("-------->"+mFriendInfo.toString(),"收到了数据长度变化 "+mChatInfoList.size());
				mAdapter.setListAll(mChatInfoList);
				mAdapter.notifyDataSetChanged();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				Logger.d("读消息出错 " + e.getMessage());
			}
		}

		@Override
		public void setDeviceName(String name) {
			Logger.d("设置设备名 " + name);
		}

		@Override
		public void showMessage(String message, int code) {
			if (!isFinishing()) {
				return;
			}
			Logger.d("展示消息 " + message);
			if (mProgressDialog != null) {
				mProgressDialog.hide();
			}

			showToast("连接失败..");
		}
	};


	/*public static void startActivity(Context context, String title,FriendInfo friendInfo) {
		Bundle bundle = new Bundle();
		bundle.putString(NAME, title);
		bundle.putSerializable(NAME,fri);
		Intent intent = new Intent(context, ChatActivity.class);
		intent.putExtra(BUNDLE, bundle);
		context.startActivity(intent);
	}*/


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_chat);

		ButterKnife.bind(this);
		initData();
	}

	private BluetoothChatHelper mBlueChatHelper;

	private void initData() {
		mBlueChatHelper = new BluetoothChatHelper(chatCallback);
     		mAdapter = new ChatAdapter(mContext);
		listView.setAdapter(mAdapter);
		mFriendInfo = this.getIntent().getParcelableExtra(Constant.FRIEND_INFO);
		if (mFriendInfo == null) {
			return;
		}
		initView();
		mProgressDialog.setMessage("连接中...");
		if (!isFinishing() && !mProgressDialog.isShowing()) {
			mProgressDialog.show();
		}

		new Handler(Looper.getMainLooper()).postDelayed(() ->
						mBlueChatHelper.connect(mFriendInfo.getBluetoothDevice(), false)
				, 3000);
	}

	private void initView() {
		mProgressDialog = new ProgressDialog(mContext);
		String title = mFriendInfo.getFriendNickName();
		if (mFriendInfo.isOnline()) {
			title = title + "(在线)";
		} else {
			title = title + "(离线)";
		}
		centerTitle.setText(title);
		setToolbar(toolbar);
		// 对话


	}

	private void initRecyclerView() {
//		xRecyclerView.setPullRefreshEnabled(false);
//		xRecyclerView.setLoadingMoreEnabled(false);
//		LinearLayoutManager manager = new LinearLayoutManager(this);
//		xRecyclerView.setLayoutManager(manager);
//		EasyBorderDividerItemDecoration itemDecoration = new EasyBorderDividerItemDecoration(getResources().getDimensionPixelOffset(R.dimen.chat_border_divider_height), 0);
//		xRecyclerView.addItemDecoration(itemDecoration);

	}

	@OnClick({R.id.chat_msg_face, R.id.chat_msg_add, R.id.chat_msg_send})
	public void onClick(View view) {
		switch (view.getId()) {
			case R.id.chat_msg_face:
				pickEmoji();
				break;
			case R.id.chat_msg_add:
				pickFile();
				break;
			case R.id.chat_msg_send:
				sendMsg();
				break;
			default:
				break;
		}
	}

	private void sendMsg() {
		if (chatMsgEdit.getText() != null && chatMsgEdit.getText().toString().trim().length() > 0) {
			sendMessage();
		} else {
			showToast("消息为空,请先输入要发送的消息！");
		}
	}

	private void sendMessage() {
		ChatInfo chatInfo = new ChatInfo();
		FriendInfo friendInfo = new FriendInfo();
		friendInfo.setBluetoothDevice(mBlueChatHelper.getAdapter().getRemoteDevice(mBlueChatHelper.getAdapter().getAddress()));
		friendInfo.setOnline(true);
		friendInfo.setFriendNickName(mBlueChatHelper.getAdapter().getName());
		friendInfo.setIdentificationName(mBlueChatHelper.getAdapter().getName());
		friendInfo.setDeviceAddress(mBlueChatHelper.getAdapter().getAddress());
		chatInfo.setFriendInfo(friendInfo);
		chatInfo.setSend(true);
		chatInfo.setSendTime(DateTime.getStringByFormat(new Date(), DateTime.DEFYMDHMS));
		BaseMessage message = null;
		if (mIsSendFile) {
			message = new FileMessage();
			message.setMsgType(ChatConstant.VISE_COMMAND_TYPE_FILE);
			message.setMsgContent(chatMsgEdit.getText().toString());
			message.setMsgLength(chatMsgEdit.getText().length());
			if (mSendFile != null) {
				((FileMessage) message).setFileLength((int) mSendFile.length());
				((FileMessage) message).setFileName(mSendFile.getName());
			}
			if (mFilePath != null) {
				((FileMessage) message).setFileNameLength(mFilePath.length());
			}
		} else {
			message = new BaseMessage();
			message.setMsgType(ChatConstant.VISE_COMMAND_TYPE_TEXT);
			message.setMsgContent(chatMsgEdit.getText().toString());
			message.setMsgLength(chatMsgEdit.getText().length());
		}
		chatInfo.setMessage(message);
		mChatInfoList.add(chatInfo);
		mAdapter.setListAll(mChatInfoList);
		chatMsgEdit.setText("");

		try {
			if (mIsSendFile && mSendFile != null) {
				mBlueChatHelper.write(CommandHelper.packFile(mSendFile));
				mIsSendFile = false;
				// 调用系统程序发送文件
//					String
				// TODO: 2018/4/23
			} else {
				mBlueChatHelper.write(CommandHelper.packMsg(message.getMsgContent()));
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			Logger.d("不被支持的转码格式错误 " + e.getMessage());
		}
	}

	private void pickFile() {

	}

	private void pickEmoji() {
	}

	@Override
	protected void onDestroy() {
		if(mProgressDialog != null){
			mProgressDialog.dismiss();
			mProgressDialog = null;
		}
		if (mBlueChatHelper != null){
			mBlueChatHelper.stop();
			mBlueChatHelper = null;
		}

		super.onDestroy();
	}
}
